jQuery(document).ready(function($) {
   $.address.strict(false).wrap(true);
   $.address.init(function(event){
      $('#jobposhead a, #invitefirstok a').address();
   }).change(function(event){
      if($.address.value() == 'interview'){
         $.address.title($.address.title().split(' | ')[0] + ' | 匹配条件');
         var target = $('#matchrulehead');
         var jobid = parseInt($('#job_id').text());
         if(!target.hasClass('cur_li')){
            var matchhead = $('#jobposhead');
            $('li.cur_li', matchhead).removeClass('cur_li').addClass('gray');
            target.removeClass('gray').addClass('cur_li');

            if(target.hasClass('has_body')){
               $('.rulesbody').hide();
               $('#interviewbody').show();
            } else {
               $.get(getjobdemands, {id:jobid}).done(function(body){
                  target.addClass('has_body');
                  matchhead.nextAll().hide();
                  matchhead.parent().append(body);
                  $("#jobdetails").show();
               });
            }
         }
      } else if($.address.value() == 'onlinetest'){
         if($('.has_interview').length){
            $.address.title($.address.title().split(' | ')[0] + ' | 线上笔试');
            var target = $('#onlinetesthead');
            var jobid = parseInt($('#job_id').text());
            if(!target.hasClass('cur_li')){
               var matchhead = $('#jobposhead');
               $('li.cur_li', matchhead).removeClass('cur_li').addClass('gray');
               target.addClass('cur_li');

               if(target.hasClass('has_body')){
                  $('.rulesbody').hide();
                  $('#onlinetestbody').show();
               } else {
                  $.get(getonlinetest, {id:jobid}).done(function(body){
                        target.addClass('has_body');
                        matchhead.nextAll().hide();
                        matchhead.parent().append(body);
                        $("#jobdetails").show();
                  });
               }
            }
         } else {
            $.address.history(false).value('interview').history(true);
         }

      } else if($.address.value() == 'persontest'){
         if($('.has_interview').length){
            $.address.title($.address.title().split(' | ')[0] + ' | 性格测试');
            var target = $('#persontesthead');
            var jobid = parseInt($('#job_id').text());
            if(!target.hasClass('cur_li')){
               var matchhead = $('#jobposhead');
               $('li.cur_li', matchhead).removeClass('cur_li').addClass('gray');
               target.removeClass('gray').addClass('cur_li');

               if(target.hasClass('has_body')){
                  $('.rulesbody').hide();
                  $('#persontestbody').show();
               } else {
                  $.get(getpersontest, {id:jobid}).done(function(body){
                     target.addClass('has_body');
                     matchhead.nextAll().hide();
                     matchhead.parent().append(body);
                     $("#jobdetails").show();
                  });
               }
            }
         } else {
            $.address.history(false).value('interview').history(true);
         }

      } else {
         $.address.history(false).value('interview').history(true);
      }
   })

   $(document).on("click", '#onlinetestbody .delete_sheet', function(e) {
      var target = $(this).parent();

      var jobid = parseInt($('#job_id').text());
      var sheetid = parseInt($('.sheetid', target).text());

      var data = {};
      data.jobid = jobid;
      data.sheetid = sheetid;

      showConfirmDialog('确认删除该试卷么？',function() {
         // Delete action
         $.ajax({
            type:"POST",
            url: del_sheet_url,
            data:data,
            dataType: "json",
            success:function(data) {
               try {
                  var retmsg = data;
                  if (retmsg.error) {
                     showMessageDialog(retmsg.error);
                     return;
                  }
                  if (retmsg.success) {
                     location.reload();
                     return;
                  }
               } catch(e) {
                  return false;
               }
            }
         });
      });
      return false;
   });

   $(document).on("showinvite", function(e, data) {
      var invitedialog = $("#invitefirstok"); 
      if(!invitedialog.hasClass("notdone"))
         return false; 

      invitedialog.removeClass('notdone').find("a[href=#"+data+"]").remove(); 
      invitedialog.show().position({
         my: 'center',
         at: 'center',
         of: $(".hr_settingwrap")
      });

      // Show invite checkbox
      $("#invitesetting").show();
   });

   if ($('#jobdetails').data('sconfirm').length > 0) {
      $('#sync_job_position .account'+$('#jobdetails').data('sconfirm')).trigger('click');
   }
   
   var jobcontent = $('#jobcontent');

   $('#jobActionPanel').on('click', '.delete', function(event) {
      var target = $(this); 
      var job = jobcontent.data('id');
      event.preventDefault();
      $.ajax({
         type: 'POST',
         url: OC.filePath('jobposition', 'ajax', 'delete.php'),
         data: {ids:JSON.stringify([job])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = jobcontent.data('jobtitle'); 
               OC.Notification.showHtml('职位<strong>'+ jobtitle + '</strong>被删除进回收站。'+'<span class="undo restoreone">撤销</span>', 3000, function(){
                  var folder =  $(".hr_inner_navigate li.cur_li a");  
                  window.location = folder.data("href") ? folder.data("href") : folder.attr("href");
               });
            }
            else {
               showMessagePanel(result.data.message, target, true, {placement:'bottom'});
            }
         }   
      });
      return false;
   });

   $('#jobActionPanel').on('click', 'a.save', function(event) {
      var target = $(this); 
      event.preventDefault();
      target.tooltip("hide");
      var job = jobcontent.data('id');
      $.ajax({
         type: "POST",
         url: OC.filePath('jobposition', 'ajax', 'save.php'),
         data: {ids:JSON.stringify([job])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = jobcontent.data('jobtitle');
               OC.Notification.showHtml('职位<strong>'+ jobtitle + '</strong>被收藏。', 3000);
               var span = target.closest('.selectedActions');
               span.html('<a class="unsave noboxradius" href="javascript:;" title="点击取消收藏简历"><i class="save"></i>已收藏</a>');
               $('a.save', span).tooltip("hide");
               $('a.unsave', span).tooltip();
            }
            else {
               showMessagePanel(result.data.message, target, true, {placement:"bottom"});
            }
         }
      });

      return false;
   });


   $('#jobActionPanel').on('click', 'a.unsave', function(event) {
      var target = $(this);
      event.preventDefault();
      target.tooltip("hide");
      var job = jobcontent.data('id');
      $.ajax({
         type: "POST",
         url: OC.filePath('jobposition', 'ajax', 'unsave.php'),
         data: {ids:JSON.stringify([job])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               var jobtitle = jobcontent.data('jobtitle');
               OC.Notification.showHtml('职位<strong>'+ jobtitle + '</strong>已被取消收藏。', 3000);
               var span = target.closest('.selectedActions');
               span.html('<a class="save noboxradius" href="javascript:;" title="点击收藏简历"><i class="unsave"></i>未收藏</a>');
               $('a.unsave', span).tooltip("hide");
               $('a.save', span).tooltip();
            }
            else {
               showMessagePanel(result.data.message, target, true, {placement:"bottom"});
            }
         }
      });
      return false;
   });

   var restoreJob = function(target, callback) {
      var job = jobcontent.data('id');
      $.ajax({
         type: "POST",
         url: OC.filePath('jobposition', 'ajax', 'restore.php'),
         data: {ids:JSON.stringify([job])},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if (result.status == 'success') {
               if($.isFunction(callback)) callback();
            }
            else {
               showMessagePanel(result.data.message, target, true, {placement:"bottom"});
            }
         }
      });
   }; 


   $('#jobActionPanel').on('click', 'a.restore', function(event) {
      event.preventDefault();
      restoreJob($(this), function() {
         var jobtitle = $(".hr_breadcrumbs .crumb.jobtitle a").text();
         OC.Notification.showHtml('职位<strong>'+ jobtitle + '</strong>已被恢复。', 3000);
      }); 
      return false;
   });
   
   $('#jobActionPanel').on('click', 'a.infolder', function(event) {
      event.preventDefault();
      var job = jobcontent.data('id');
      
      var scrolltop = $(window).scrollTop();
      $("#infolder_modal").css({top:scrolltop+75}).modal('show');
      
      $.ajax({
         type: "GET",
         url: OC.filePath('jobposition', 'ajax', 'getinfolderlist.php'),
         data: {ids:JSON.stringify([job])},
         beforeSend: function(xhr, settings) {
            showLoading($("#infolder_body"));
         },
         success: function(result){
            $("#infolder_body").html(result);
         }
      });
      
      return false; 
   });

   $('#notification').on('click', '.undo', function(){
      OC.Notification.clear();
      if($(this).hasClass("restoreone")) {
         restoreJob($(this)); 
      }

      OC.Notification.hide();
      return false; 
   });
   
   // folder manage
   $('#folder_dropdown').on('click', '.showlist', function() {
      $('#foldermanage_modal').modal('show');
      $.ajax({
         url: OC.filePath('jobposition', 'ajax', 'getcustomfolderlist.php'),
         data: {searchurl: $('#folder_dropdown').data('searchurl')},
         beforeSend: function(xhr, settings) {
            showLoading($("#foldermanage_body"));
         },
         success: function(data) {
            $("#foldermanage_body").html(data);
         }
      });
   });
})
